package com.example.baiduai.model;

import okhttp3.*;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
public class Sample {

    public static final String API_KEY = "EPcUIB9rKL0j5QwGlumDDb3Q";
    public static final String SECRET_KEY = "WCWQZQvKXun5z9OrjUYeD1p2PIdSea6d";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    public String outResult(String json) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        System.out.println();
        Request request = new Request.Builder().url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/yi_34b_chat?" +
                "access_token=24.61983a73ef932f4885c230ba3b818168.2592000.1714722529.282335-59349579").method("POST", body)
                .addHeader("Content-Type", "application/json").build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        System.out.println(request.url());
        System.out.println(response.body());
        return response.body().string();
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder().url("https://aip.baidubce.com/oauth/2.0/token").method("POST", body).addHeader("Content-Type", "application/x-www-form-urlencoded").build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
